package com.gary.demo.biz.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gary.demo.biz.GoodsBO;
import com.gary.demo.common.enums.GoodsStatusEnum;
import com.gary.demo.common.model.LoginHolder;
import com.gary.demo.common.utils.CheckUtil;
import com.gary.demo.dao.GoodsMapper;
import com.gary.demo.entity.Goods;
import com.gary.demo.model.param.GoodsOperateParam;
import com.gary.demo.model.param.GoodsQueryParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GoodsBOImpl implements GoodsBO {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private LoginHolder loginHolder;
    @Override
    public Integer add(GoodsOperateParam param) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(param,goods);
        goods.setCreator(loginHolder.currentUser().getUserName());
        goods.setStatus(GoodsStatusEnum.NULL.getCode());
        goodsMapper.insert(goods);
        return goods.getId();
    }

    @Override
    public void update(GoodsOperateParam param) {
        Goods goods = goodsMapper.selectById(param.getId());
        CheckUtil.isNull(goods,"未查询对应的商品信息");
        LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(Goods::getId, param.getId());
        updateWrapper.set(Goods::getGoodsName, param.getGoodsName());
        updateWrapper.set(Goods::getRemark, param.getRemark());
        updateWrapper.set(Goods::getPrice, param.getPrice());
        updateWrapper.set(Goods::getModifier, loginHolder.currentUser().getUserName());
        goodsMapper.update(null, updateWrapper);

    }

    @Override
    public Goods getById(Integer id) {
        return goodsMapper.selectById(id);
    }

    @Override
    public IPage<Goods> pageQuery(GoodsQueryParam param) {
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(param.getStatus())) {
            queryWrapper.eq(Goods::getStatus, param.getStatus());
        }
        if (StrUtil.isNotBlank(param.getGoodsName())) {
            queryWrapper.like(Goods::getGoodsName,param.getGoodsName());
        }
        IPage<Goods> page = new Page<>(param.getPageNum(), param.getPageSize());
        IPage<Goods> goodsIPage = goodsMapper.selectPage(page, queryWrapper);
        return goodsIPage;
    }
}
